package com.longyi.admin.controller;

import com.longyi.admin.annotation.Logging;
import com.longyi.admin.entity.RoleMenu;
import com.longyi.admin.entity.User;
import com.longyi.admin.service.RoleMenuService;
import com.longyi.admin.service.RoleService;
import com.longyi.admin.entity.Role;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

import com.longyi.admin.common.QueryPageParam;
import com.longyi.admin.common.Result;

/**
* Role 前端控制器
*
* @author 龙毅
* @since 2025-09-08
*/
@RestController
@RequestMapping("/role")
public class RoleController {

    // 注入service
    @Autowired
    private RoleService roleService;
    @Autowired
    private RoleMenuService roleMenuService;

    // 统计数量
    @GetMapping("/count")
    public Integer count() {
        return roleService.count();
    }

    // 获取列表
    @GetMapping("/list")
    public List<Role> list() {
        return roleService.list();
    }

    // 新增数据
    @PostMapping("/save")
    public Result save(@RequestBody Role role) {
        return roleService.save(role) 
            ? Result.suc("新增成功") 
            : Result.fail("新增失败");
    }

    // 修改数据
    @PostMapping("/update")
    public Result update(@RequestBody Role role) {
        return roleService.updateById(role)
            ? Result.suc("修改成功") 
            : Result.fail("修改失败");
    }

    // 获取详情
    @GetMapping("/info/{id}")
    public Result info(@PathVariable("id") Long id) {
        Role role = roleService.getById(id);
        List<RoleMenu> list=roleMenuService.lambdaQuery().eq(RoleMenu::getRoleId, id).list();
        List<Long> ids=list.stream().map(p->p.getMenuId()).collect(Collectors.toList());
        HashMap res=new HashMap();
        res.put("role", role);
        res.put("ids", ids);
        return Result.suc(res);
    }

    //分配权限
    @Transactional
    @Logging(record = "分配权限", type = "分配权限")
    @PostMapping("/perm/{id}/{ids}")
    public Result perm(@PathVariable("id") Long id, @PathVariable("ids") Long[] ids) {
       List<Long> list=roleMenuService.lambdaQuery().eq(RoleMenu::getRoleId, id).list().stream().map(p->p.getId()).collect(Collectors.toList());
        System.out.println(list);
       roleMenuService.removeByIds(list);
       for (Long menuId : ids){
           RoleMenu roleMenu=new RoleMenu();
           roleMenu.setRoleId(id);
           roleMenu.setMenuId(menuId);
           roleMenuService.save(roleMenu);
       }
       return Result.suc("分配权限成功");
    }
    // 批量删除数据
    @Transactional
    @PostMapping("/deleteBatch")
    public Result deleteBatch(@RequestBody Long[] ids) {
        roleService.removeByIds(Arrays.asList(ids));
        return Result.suc("批量删除成功");
    }

    // 分页查询
    @PostMapping("/listPage")
    public Result listPage(@RequestBody QueryPageParam query) {
        HashMap param = query.getParam();

        // 提取查询参数
            String id = (String) param.get("id");
            String name = (String) param.get("name");
            String code = (String) param.get("code");
            String remark = (String) param.get("remark");
            String createTime = (String) param.get("createTime");
            String status = (String) param.get("status");
            String register = (String) param.get("register");

        // 分页配置
        Page<Role> page = new Page<>();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());

        // 构建查询条件
        LambdaQueryWrapper<Role> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                if (StringUtils.isNotBlank(name) && !"null".equals(name)) {
                    lambdaQueryWrapper.like(Role::getName, name);
                }
                if (StringUtils.isNotBlank(code) && !"null".equals(code)) {
                    lambdaQueryWrapper.like(Role::getCode, code);
                }
                if (StringUtils.isNotBlank(remark) && !"null".equals(remark)) {
                    lambdaQueryWrapper.like(Role::getRemark, remark);
                }
                if (StringUtils.isNotBlank(createTime) && !"null".equals(createTime)) {
                    lambdaQueryWrapper.like(Role::getCreateTime, createTime);
                }
                if (StringUtils.isNotBlank(status) && !"null".equals(status)) {
                    lambdaQueryWrapper.eq(Role::getStatus, status);
                }
                if (StringUtils.isNotBlank(register) && !"null".equals(register)) {
                    lambdaQueryWrapper.eq(Role::getRegister, register);
                }

        // 执行分页查询
        IPage result = roleService.PageList(page, lambdaQueryWrapper);
        return Result.suc(result.getTotal(), result.getRecords());
    }
    @PostMapping("/modStatus/{id}")
    @Logging(record = "修改角色状态", type = "修改")
    public Result modStatus(@PathVariable("id") Long id) {
        Role role = roleService.getById(id);
        role.setStatus(role.getStatus()==1?0:1);
        return roleService.updateById(role)?Result.suc("修改成功") : Result.fail("修改失败");
    }
    @PostMapping("/modRegisterStatus/{id}")
    public Result modRegisterStatus(@PathVariable("id") Long id) {
        Role role = roleService.getById(id);
        role.setRegister(role.getRegister()==1?0:1);
        return roleService.updateById(role)?Result.suc("修改成功") : Result.fail("修改失败");
    }
}